package com.leosoft.heatmonitor.control;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.leosoft.heatmonitor.model.Project;
import com.leosoft.heatmonitor.service.transactional.TargetService;

@Controller
@RequestMapping("/target")
public class TargetController {
	@Autowired(required = true)
	TargetService targetService;

	String[] columns = { "projectName", "building", "door", "user", "key", "name", "telephone", "id", };

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request) {
		String username = getUserName();
		int startIndex = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String draw = request.getParameter("draw");

		List<String[]> odrerPart = new ArrayList<>();
		List<String[]> wherePart = new ArrayList<>();

		for (int i = 0; i < columns.length; i++) {
			String orderColumn = request.getParameter("order[" + i + "][column]");
			if (orderColumn != null) {
				String orderDir = request.getParameter("order[" + i + "][dir]");
				odrerPart.add(new String[] { columns[Integer.parseInt(orderColumn)], orderDir });
			}
		}

		for (int i = 0; i < columns.length; i++) {
			String searchable = request.getParameter("columns[" + i + "][searchable]");
			if (searchable.equals("true")) {
				String searchColumn = columns[i];
				String value = request.getParameter("columns[" + i + "][search][value]");
				if (!value.isEmpty()) {
					wherePart.add(new String[] { searchColumn, value });
				}
			}
		}

		Map<String, Object> result = targetService.list(startIndex, length, wherePart, odrerPart, username);
		result.put("draw", draw);
		return result;
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	ModelAndView create(@RequestParam("projectId") String projectId, @RequestParam("building") String building,
			@RequestParam("door") String door, @RequestParam("user") String user, @RequestParam("key") String key,
			@RequestParam("name") String name, @RequestParam("telephone") String telephone) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("nav", "target");
		mv.setViewName("home");
		if (!targetService.create(projectId, building, door, user, key, name, telephone)) {
			mv.addObject("error", "创建用户失败: 重复的用户!");
		}
		return mv;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	String delete(@RequestParam("id") String id) {
		targetService.delete(id);
		return "redirect:/home/target";
	}

	@RequestMapping(value = "/loadProject", method = RequestMethod.POST)
	@ResponseBody
	Project loadProject(@RequestParam("id") String id) {
		return targetService.loadProject(id);
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	String update(@RequestParam("id") String id, @RequestParam("projectId") String projectId,
			@RequestParam("building") String building, @RequestParam("door") String door,
			@RequestParam("user") String user, @RequestParam("key") String key, @RequestParam("name") String name,
			@RequestParam("telephone") String telephone) {
		targetService.update(id, projectId, building, door, user, key, name, telephone);
		return "redirect:/home/target";
	}

	@RequestMapping(value = "/loadTarget")
	@ResponseBody
	List<Map<String, Object>> loadTarget(@RequestParam("id") String projectId, @RequestParam("deviceId") String deviceId) {
		return targetService.loadTarget(projectId, deviceId);
	}

	@RequestMapping(value = "/loadBuilding")
	@ResponseBody
	List<Object> loadBuilding(@RequestParam("projectId") String projectId) {
		return targetService.loadBuilding(projectId);
	}

	@RequestMapping(value = "/loadDoor")
	@ResponseBody
	List<Object> loadDoor(@RequestParam("projectId") String projectId, @RequestParam("building") String building) {
		return targetService.loadDoor(projectId, building);
	}

	@RequestMapping(value = "/suggest/building/{building}")
	@ResponseBody
	public List<String> suggestBuilding(@PathVariable(value = "building") String building)
			throws UnsupportedEncodingException {
		String username = getUserName();
		return targetService.suggestBuilding(building, username);
	}

	@RequestMapping(value = "/suggest/door/{door}")
	@ResponseBody
	public List<String> suggestDoor(@PathVariable(value = "door") String door) throws UnsupportedEncodingException {
		String username = getUserName();
		return targetService.suggestDoor(door, username);
	}

	@RequestMapping(value = "/suggest/user/{user}")
	@ResponseBody
	public List<String> suggestUser(@PathVariable(value = "user") String user) throws UnsupportedEncodingException {
		String username = getUserName();
		return targetService.suggestUser(user, username);
	}

	@RequestMapping(value = "/suggest/key/{key}")
	@ResponseBody
	public List<String> suggestKey(@PathVariable(value = "key") String key) throws UnsupportedEncodingException {
		String username = getUserName();
		return targetService.suggestKey(key, username);
	}

	@RequestMapping(value = "/upload")
	public ModelAndView uploadShipments(@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam("projectId") String projectId, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("home");
		mv.addObject("nav", "target");
		if (targetService.upload(file, projectId)) {
			mv.addObject("error", "Upload Success!");
		}
		return mv;
	}

	String getUserName() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username;
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		return username;
	}
}
